﻿using JNPF.Basics.Logic;
using JNPF.Basics.Models;
using JNPF.Basics.Models.WeChat.Dtos.MPMaterial;
using JNPF.Utils;
using JNPF.Utils.Controller;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace JNPF.Basics.Controller
{
    /// <summary>
    /// 公众号素材
    /// 版 本：V3.0.0
    /// 版 权：引迈信息技术有限公司（https://www.jnpfsoft.com）
    /// 作 者：JNPF开发平台组
    /// 日 期：2018-09-18 
    /// </summary>
    [Route("api/WeChat/[controller]")]
    public class MPMaterialController : BaseApiController
    {
        private MPMaterialBll mPMaterialBll = new MPMaterialBll();
        private UserBll userBll = new UserBll();

        #region Get
        /// <summary>
        /// 列表
        /// </summary>
        /// <param name="Input">请求参数</param>
        /// <param name="type">素材类型</param>
        /// <returns></returns>
        [HttpGet("{type}")]
        public async Task<ResponseResult> GetList([FromQuery] PageInput Input, int type)
        {
            var data = await mPMaterialBll.GetList(type, Input);
            var list = data.list.Select(x => new MPMaterialListOutput()
            {
                author = x.Author,
                contentSourceUrl = x.ContentSourceUrl,
                digest = x.Digest,
                enabledMark = x.EnabledMark,
                fileJson = x.FileJson,
                id = x.Id,
                mediaId = x.MediaId,
                returnUrl = "/api/Common/Image/weixin/" + x.FileJson,
                title = x.Title,
                uploadDate = x.UploadDate,
                uploadUser = userBll.GetUserName(x.UploadUser)
            });
            var output = new PageResult()
            {
                list = list,
                pagination = data.pagination
            };
            return Success(output);
        }

        /// <summary>
        /// 显示图片
        /// </summary>
        /// <param name="fileName">文件名称、注意 后缀名前端故意把 .替换@ </param>
        /// <returns></returns>
        [HttpGet("ShowImg/{fileName}")]
        [AllowAnonymous]
        public FileContentResult GetShowImg(string fileName)
        {
            var imgPath = ConfigurationKey.MPMaterialFilePath + fileName.Replace("@", ".");
            var imgByte = FileHelper.ReadAllBytes(imgPath);
            var imgStream = new MemoryStream(imgByte);
            return File(imgStream.ToArray(), @"image/jpg");
        }
        #endregion

        #region POST
        /// <summary>
        /// 上传附件
        /// </summary>
        /// <returns></returns>
        [HttpPost("UploadFile")]
        public async Task<ResponseResult> UploadFile()
        {
            Thread.Sleep(1000);
            var file = Utils.HttpContext.Current.Request.Form.Files[0];
            var fileType = Path.GetExtension(file.FileName).Replace(".", "");
            if (!this.AllowFileType(fileType))
            {
                return Error("上传失败，文件格式不允许上传");
            }
            var _filePath = ConfigurationKey.TemporaryFilePath;
            var _fileName = DateTime.Now.ToString("yyyyMMdd") + "_" + CommonHelper.Guid.ToString() + Path.GetExtension(file.FileName);
            using (var stream = new FileStream(_filePath + _fileName, FileMode.Create))
            {
                file.CopyTo(stream);
            }
            var response = new
            {
                fileName = _fileName,
                creatorTime = DateTime.Now
            };
            return Success("上传成功", response);
        }

        /// <summary>
        /// 上传封面
        /// </summary>
        /// <returns></returns>
        [HttpPost("UploadCover")]
        public async Task<ResponseResult> UploadCover()
        {
            var file = Utils.HttpContext.Current.Request.Form.Files[0];
            var ImgType = Path.GetExtension(file.FileName).Replace(".", "");
            if (!this.AllowFileType(ImgType))
            {
                return Error("上传失败，图片格式不允许上传");
            }
            var filePath = ConfigurationKey.TemporaryFilePath;
            var fileName = DateTime.Now.ToString("yyyyMMdd") + "_" + CommonHelper.Guid.ToString() + Path.GetExtension(file.FileName);
            using (var stream = new FileStream(filePath + fileName, FileMode.Create))
            {
                file.CopyTo(stream);
            }
            return Success("上传成功", fileName);
        }

        /// <summary>
        /// 上传永久素材(图片（image）、语音（voice）和缩略图（thumb）)
        /// </summary>
        /// <param name="Input">实体对象</param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<ResponseResult> UploadForeverMedia([FromBody] MPMaterialUpLoadInput Input)
        {
            var entity = Input.MapTo<MPMaterialEntity>();
            await mPMaterialBll.UploadForeverMedia(entity);
            return Success("上传成功");
        }

        /// <summary>
        /// 上传永久视频素材
        /// </summary>
        /// <param name="Input">实体对象</param>
        [HttpPost("UploadForeverVideo")]
        [AllowAnonymous]
        public async Task<ResponseResult> UploadForeverVideo([FromBody] MPMaterialUpLoadInput Input)
        {
            var entity = Input.MapTo<MPMaterialEntity>();
            await mPMaterialBll.UploadForeverVideo(entity);
            return Success("上传成功");
        }

        /// <summary>
        /// 上传永久图文素材
        /// </summary>
        /// <param name="Input">实体对象</param>
        [HttpPost("UploadNews")]
        [AllowAnonymous]
        public async Task<ResponseResult> UploadNews([FromBody] MPMaterialUpLoadInput Input)
        {
            var entity = Input.MapTo<MPMaterialEntity>();
            await mPMaterialBll.UploadNews(entity);
            return Success("上传成功");
        }
        /// <summary>
        /// 删除永久素材
        /// </summary>
        /// <param name="mediaId">永久素材主键</param>
        [HttpDelete("{id}")]
        [AllowAnonymous]
        public async Task<ResponseResult> DeleteForeverMedia(string id)
        {
            var entity = await mPMaterialBll.GetInfo(id);
            await mPMaterialBll.DeleteForeverMedia(entity);
            return Success("删除成功");
        }
        #endregion

        #region Method
        /// <summary>
        /// 允许文件类型
        /// </summary>
        /// <param name="fileExtension">文件后缀名</param>
        /// <returns></returns>
        private bool AllowFileType(string fileExtension)
        {
            var isOk = false;
            var allowExtension = ConfigurationKey.MPUploadFileType;
            foreach (var item in allowExtension)
            {
                if (item == fileExtension.ToLower())
                {
                    isOk = true;
                    break;
                }
                else
                {
                    isOk = false;
                }
            }
            return isOk;
        }
        #endregion
    }
}